package com.isyscore.os.core.exception;

import com.isyscore.device.common.exception.BaseException;
import lombok.Getter;

import java.text.MessageFormat;
import java.util.Objects;

/**
 * @author felixu
 * @since 2021.05.10
 */
@Getter
public class DataFactoryException extends BaseException {

    private final ErrorCode error;

    private final Object[] args;

    public DataFactoryException(ErrorCode error) {
        this(error, (Object) null);
    }

    public DataFactoryException(ErrorCode error, Object... args) {
        super(error, args);
        this.error = error;
        this.args = args;
    }

    @Override
    public String getMessage() {
        ErrorCode error = this.getError();
        String message = error.getMessage();
        if (Objects.nonNull(this.getArgs()) && this.getArgs().length > 0) {
            message = MessageFormat.format(message, this.getArgs());
        }
        return message;
    }

    public static String getMessage(Throwable e) {
        String message;
        if (e instanceof DataFactoryException) {
            DataFactoryException ex = (DataFactoryException) e;
            ErrorCode error = ex.getError();
            message = error.getMessage();
            if (Objects.nonNull(ex.getArgs()) && ex.getArgs().length > 0) {
                message = MessageFormat.format(message, ex.getArgs());
            }
        } else {
            message = e.getMessage();
        }
        return message;
    }

}
